'use strict'
import React, { Component } from 'react'
import { StyleSheet, RefreshControl } from 'react-native'
import PropTypes from 'prop-types'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

export default class CDScrollView extends Component {
  constructor(props) {
    super(props)
    this.state = {
      refreshing: false,
    }
  }

  static propTypes = {
    ...KeyboardAwareScrollView.propTypes,
    extraScrollHeight: PropTypes.number,
    didMountRefresh: PropTypes.bool,
    onPullDown: PropTypes.func, // 返回promise
  }

  static defaultProps = {
    didMountRefresh: false,
    extraScrollHeight: 40,
  }

  componentDidMount() {
    if (this.props.didMountRefresh && this.props.onPullDown) {
      this._pullDownRefresh()
    }
  }

  _refreshControl = () => {
    if (this.props.onPullDown) {
      return (
        <RefreshControl
          refreshing={this.state.refreshing}
          onRefresh={this._pullDownRefresh}
        />
      )
    }
  }

  _pullDownRefresh = () => {
    if (!this.props.onPullDown) return
    if (!this.state.refreshing) {
      this.setState(
        {
          refreshing: true,
        },
        () => {
          this.props
            .onPullDown()
            .then(() => {
              this.setState({
                refreshing: false,
              })
            })
            .catch((e) => {
              this.setState({
                refreshing: false,
              })
            })
        }
      )
    } else {
      this.setState({
        refreshing: false,
      })
    }
  }

  scrollTo = (x = 0, y = 0, animated = true) => {
    if (
      this.handleRefScrollView &&
      this.handleRefScrollView.scrollResponderScrollTo
    ) {
      this.handleRefScrollView.scrollResponderScrollTo(x, y, animated)
    }
  }

  scrollToEnd = (animated = true) => {
    if (
      this.handleRefScrollView &&
      this.scrollResponderScrollToEnd.scrollToEnd
    ) {
      this.handleRefScrollView.scrollResponderScrollToEnd(animated)
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView
        {...this.props}
        extraScrollHeight={this.props.extraScrollHeight}
        innerRef={(e) => {
          this.handleRefScrollView = e
        }}
        style={[styles.container, this.props.style]}
        keyboardShouldPersistTaps='handled'
        refreshControl={this._refreshControl()}
      >
        {this.props.children}
      </KeyboardAwareScrollView>
    )
  }
}

const styles = StyleSheet.create({
  container: {},
})
